package test.juzi;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

/**
 * HttpURLConnection工具类
 * 
 * @author chenglu
 * 
 */
public class HttpUrlConnectionUtil {

	public static URL url = null;
	public static HttpURLConnection httpUrlConnection = null;

	/**
	 * 获得HttpUrlConnection对象
	 */
	public static HttpURLConnection getHttpUrlConnection(String urlpath) {
		try {
			url = new URL(urlpath);
			httpUrlConnection = (HttpURLConnection) url.openConnection();
			// 此处的urlConnection对象实际上是根据URL的
			// 请求协议(此处是http)生成的URLConnection类
			// 的子类HttpURLConnection,故此处最好将其转化
			// 为HttpURLConnection类型的对象,以便用到
			// HttpURLConnection更多的API.如下:
			httpUrlConnection.setRequestProperty("User-Agent",
					"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727)");// 增加报头，模拟浏览器，防止屏蔽
			httpUrlConnection.setRequestProperty("Accept", "*/*");// 只接受text/html类型，当然也可以接受图片,pdf,*/*任意，就是tomcat/conf/web里面定义那些
			httpUrlConnection.setRequestMethod("GET");
			httpUrlConnection.setReadTimeout(1);
			httpUrlConnection.setConnectTimeout(10000);

			// setConnectTimeout：设置连接主机超时（单位：毫秒）
			// setReadTimeout：设置从主机读取数据超时（单位：毫秒）

			// Post 请求不能使用缓存
			httpUrlConnection.setUseCaches(true);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return httpUrlConnection;
	}

	/**
	 * 关闭 HttpURLConnection
	 * 
	 * @param httpUrlConnection
	 */
	public static void closeHttpURLConnection(HttpURLConnection httpUrlConnection) {
		if (httpUrlConnection != null) {
			httpUrlConnection.disconnect();
		}
	}

	// public static JSONObject parsetoJSONObject(String urlstr) {
	// String sbStr = "";
	// InputStream inStrm = null;
	// BufferedReader reader = null;
	// HttpURLConnection httpUrl = null;
	// JSONObject json = null;
	// try {
	// httpUrl = HttpUrlConnectionUtil.getHttpUrlConnection(urlstr);
	// inStrm = httpUrl.getInputStream();
	// reader = new BufferedReader(new InputStreamReader(inStrm,"utf-8"));
	// String line = null;
	// StringBuffer sb = new StringBuffer();
	// while((line = reader.readLine())!=null){
	// sb.append(line).append("\r\n");
	// }
	// if(reader != null){
	// reader.close();
	// }
	// if(httpUrl != null){
	// httpUrl.disconnect();
	// }
	// sbStr = sb.toString();
	// // System.out.println(sbStr);
	//
	// } catch (UnsupportedEncodingException e) {
	// // TODO Auto-generated catch block
	// e.printStackTrace();
	// } catch (IOException e) {
	// // TODO Auto-generated catch block
	// e.printStackTrace();
	// }
	// JSONObject.fromString(sbStr);
	// return json;
	// }

	public static String parseToString(String urlstr, String encode) throws IOException {
		String sbStr = new String();
		InputStream inStrm = null;
		BufferedReader reader = null;
		HttpURLConnection httpUrl = null;
		try {

			httpUrl = HttpUrlConnectionUtil.getHttpUrlConnection(urlstr);
			inStrm = httpUrl.getInputStream();
			reader = new BufferedReader(new InputStreamReader(inStrm, encode));
			String line = null;
			StringBuffer sb = new StringBuffer();
			while ((line = reader.readLine()) != null) {
				sb.append(line).append("\r\n");
			}
			if (reader != null) {
				reader.close();
			}
			if (httpUrl != null) {
				httpUrl.disconnect();
			}
			sbStr = sb.toString();
		} catch (Exception e) {
			sbStr = null;
		}

		return sbStr;
	}

	public static String sendGet(String url) {
		String result = "";
		BufferedReader in = null;
		URLConnection connection = null;
		try {
			String urlNameString = url;
			URL realUrl = new URL(urlNameString);
			// 打开和URL之间的连接
			connection = realUrl.openConnection();
			// 设置通用的请求属性
			connection.setRequestProperty("accept", "*/*");
			connection.setRequestProperty("connection", "Keep-Alive");
			connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// 建立实际的连接
			connection.connect();
			// 定义 BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 使用finally块来关闭输入流
		finally {
			try {
				if (in != null) {
					in.close();
				}
				
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		return result;
	}

	public static String sendPost(String url, String param) {
		PrintWriter out = null;
		BufferedReader in = null;
		String result = "";
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
			// 设置通用的请求属性

			conn.setRequestMethod("POST");
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent", "directclient");
			// 发送POST请求必须设置如下两行

			conn.setDoOutput(true);
			conn.setDoInput(true);
			// 获取URLConnection对象对应的输出流

			out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), "utf-8"));// conn.getOutputStream()

			// 发送请求参数

			out.print(param);
			// flush输出流的缓冲

			out.flush();
			// 定义BufferedReader输入流来读取URL的响应

			in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 使用finally块来关闭输出流、输入流

		finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (Exception ex) {

			}
		}

		return result;
	}

}
